<template>
  <div class="search-container">
    <!-- 搜索按钮 -->
    <button class="search-trigger" @click="toggleSearch">
      <span class="search-icon">🔍</span>
    </button>

    <!-- 搜索面板 -->
    <div class="search-panel" :class="{ 'active': isSearchOpen }">
      <div class="search-header">
        <div class="search-input-wrapper">
          <span class="search-icon">🔍</span>
          <input 
            ref="searchInput"
            v-model="searchQuery"
            type="text"
            class="search-input"
            placeholder="搜索商品、会员、订单..."
            @input="handleSearch"
            @keydown.enter="handleEnter"
            @keydown.escape="closeSearch"
          />
          <button v-if="searchQuery" class="clear-btn" @click="clearSearch">
            <span>✕</span>
          </button>
        </div>
        <button class="close-btn" @click="closeSearch">
          <span>✕</span>
        </button>
      </div>

      <!-- 搜索过滤器 -->
      <div class="search-filters">
        <button 
          v-for="filter in searchFilters"
          :key="filter.type"
          class="filter-btn"
          :class="{ 'active': activeFilter === filter.type }"
          @click="setActiveFilter(filter.type)"
        >
          {{ filter.label }}
        </button>
      </div>

      <!-- 搜索结果 -->
      <div class="search-results" v-if="searchQuery">
        <div v-if="isLoading" class="loading">
          <span class="loading-text">搜索中...</span>
        </div>
        
        <div v-else-if="searchResults.length === 0" class="no-results">
          <span class="no-results-icon">🔍</span>
          <span class="no-results-text">未找到相关结果</span>
        </div>
        
        <div v-else class="results-list">
          <div 
            v-for="result in searchResults" 
            :key="result.id"
            class="result-item"
            @click="selectResult(result)"
          >
            <div class="result-icon">{{ result.icon }}</div>
            <div class="result-content">
              <div class="result-title">{{ result.title }}</div>
              <div class="result-subtitle">{{ result.subtitle }}</div>
            </div>
            <div class="result-action">
              <span class="action-text">{{ result.action }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 搜索建议 -->
      <div class="search-suggestions" v-else>
        <div class="suggestions-header">
          <span class="suggestions-title">快速搜索</span>
        </div>
        <div class="suggestions-list">
          <div 
            v-for="suggestion in searchSuggestions"
            :key="suggestion.id"
            class="suggestion-item"
            @click="selectSuggestion(suggestion)"
          >
            <span class="suggestion-icon">{{ suggestion.icon }}</span>
            <span class="suggestion-text">{{ suggestion.text }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 搜索遮罩层 -->
    <div 
      class="search-overlay" 
      v-show="isSearchOpen"
      @click="closeSearch"
    ></div>
  </div>
</template>

<script setup>
import { ref, computed, nextTick, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 响应式数据
const isSearchOpen = ref(false)
const searchQuery = ref('')
const activeFilter = ref('all')
const isLoading = ref(false)
const searchInput = ref(null)

// 搜索过滤器
const searchFilters = [
  { type: 'all', label: '全部' },
  { type: 'products', label: '商品' },
  { type: 'members', label: '会员' },
  { type: 'orders', label: '订单' }
]

// 搜索建议
const searchSuggestions = [
  { id: 1, icon: '📦', text: '热门商品', action: 'view_products' },
  { id: 2, icon: '👥', text: '会员查询', action: 'view_members' },
  { id: 3, icon: '📋', text: '今日订单', action: 'view_orders' },
  { id: 4, icon: '💰', text: '快速收银', action: 'start_pos' }
]

// 搜索结果
const searchResults = ref([])

// 切换搜索面板
const toggleSearch = () => {
  isSearchOpen.value = !isSearchOpen.value
  if (isSearchOpen.value) {
    nextTick(() => {
      searchInput.value?.focus()
    })
  }
}

// 关闭搜索
const closeSearch = () => {
  isSearchOpen.value = false
  searchQuery.value = ''
  searchResults.value = []
}

// 清除搜索
const clearSearch = () => {
  searchQuery.value = ''
  searchResults.value = []
}

// 设置活动过滤器
const setActiveFilter = (filterType) => {
  activeFilter.value = filterType
  if (searchQuery.value) {
    handleSearch()
  }
}

// 处理搜索
const handleSearch = () => {
  if (!searchQuery.value.trim()) {
    searchResults.value = []
    return
  }

  isLoading.value = true
  
  // 模拟搜索延迟
  setTimeout(() => {
    performSearch()
    isLoading.value = false
  }, 300)
}

// 执行搜索
const performSearch = () => {
  const query = searchQuery.value.toLowerCase()
  
  // 模拟搜索结果
  const mockResults = [
    {
      id: 1,
      type: 'product',
      title: '苹果 iPhone 15',
      subtitle: '商品编号: P001',
      icon: '📱',
      action: '查看详情'
    },
    {
      id: 2,
      type: 'member',
      title: '张三',
      subtitle: '会员号: M001',
      icon: '👤',
      action: '查看会员'
    },
    {
      id: 3,
      type: 'order',
      title: '订单 #20241201001',
      subtitle: '金额: ¥128.50',
      icon: '📋',
      action: '查看订单'
    }
  ]

  // 根据过滤器和查询过滤结果
  let filteredResults = mockResults
  
  if (activeFilter.value !== 'all') {
    const filterMap = {
      products: 'product',
      members: 'member',
      orders: 'order'
    }
    filteredResults = mockResults.filter(result => result.type === filterMap[activeFilter.value])
  }

  searchResults.value = filteredResults.filter(result => 
    result.title.toLowerCase().includes(query) || 
    result.subtitle.toLowerCase().includes(query)
  )
}

// 处理回车键
const handleEnter = () => {
  if (searchResults.value.length > 0) {
    selectResult(searchResults.value[0])
  }
}

// 选择搜索结果
const selectResult = (result) => {
  console.log('选择结果:', result)
  closeSearch()
  
  // 根据结果类型执行相应操作
  switch (result.type) {
    case 'product':
      router.push('/inventory')
      break
    case 'member':
      router.push('/members')
      break
    case 'order':
      router.push('/reports')
      break
  }
}

// 选择搜索建议
const selectSuggestion = (suggestion) => {
  console.log('选择建议:', suggestion)
  closeSearch()
  
  // 根据建议执行相应操作
  switch (suggestion.action) {
    case 'view_products':
      router.push('/inventory')
      break
    case 'view_members':
      router.push('/members')
      break
    case 'view_orders':
      router.push('/reports')
      break
    case 'start_pos':
      router.push('/pos')
      break
  }
}

// 键盘事件处理
const handleKeydown = (event) => {
  if (event.key === 'Escape' && isSearchOpen.value) {
    closeSearch()
  }
}

// 生命周期
onMounted(() => {
  document.addEventListener('keydown', handleKeydown)
})

onUnmounted(() => {
  document.removeEventListener('keydown', handleKeydown)
})
</script>

<style scoped>
.search-container {
  position: relative;
}

.search-trigger {
  background: none;
  border: none;
  padding: 8px;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.search-trigger:hover {
  background: #f5f7fa;
}

.search-icon {
  font-size: 18px;
  color: #606266;
}

/* 搜索面板 */
.search-panel {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background: white;
  z-index: 1002;
  transform: translateY(-100%);
  transition: transform 0.3s ease;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  max-height: 80vh;
  overflow-y: auto;
}

.search-panel.active {
  transform: translateY(0);
}

.search-header {
  display: flex;
  align-items: center;
  padding: 20px 30px;
  border-bottom: 1px solid #e4e7ed;
  gap: 15px;
}

.search-input-wrapper {
  flex: 1;
  display: flex;
  align-items: center;
  background: #f5f7fa;
  border-radius: 8px;
  padding: 12px 16px;
  gap: 12px;
}

.search-input {
  flex: 1;
  border: none;
  background: none;
  outline: none;
  font-size: 16px;
  color: #303133;
}

.search-input::placeholder {
  color: #909399;
}

.clear-btn {
  background: none;
  border: none;
  color: #909399;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: color 0.3s ease;
}

.clear-btn:hover {
  color: #606266;
}

.close-btn {
  background: none;
  border: none;
  color: #606266;
  cursor: pointer;
  padding: 8px;
  border-radius: 6px;
  transition: background-color 0.3s ease;
}

.close-btn:hover {
  background: #f5f7fa;
}

/* 搜索过滤器 */
.search-filters {
  display: flex;
  gap: 8px;
  padding: 15px 30px;
  border-bottom: 1px solid #e4e7ed;
}

.filter-btn {
  padding: 6px 16px;
  border: 1px solid #e4e7ed;
  border-radius: 20px;
  background: white;
  color: #606266;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
}

.filter-btn:hover {
  border-color: #409eff;
  color: #409eff;
}

.filter-btn.active {
  background: #409eff;
  border-color: #409eff;
  color: white;
}

/* 搜索结果 */
.search-results {
  padding: 20px 30px;
}

.loading {
  display: flex;
  justify-content: center;
  padding: 40px;
}

.loading-text {
  color: #909399;
  font-size: 14px;
}

.no-results {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px;
  color: #909399;
}

.no-results-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.no-results-text {
  font-size: 14px;
}

.results-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.result-item {
  display: flex;
  align-items: center;
  padding: 12px;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.3s ease;
  gap: 12px;
}

.result-item:hover {
  background: #f5f7fa;
}

.result-icon {
  font-size: 24px;
  width: 40px;
  text-align: center;
}

.result-content {
  flex: 1;
}

.result-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.result-subtitle {
  font-size: 14px;
  color: #606266;
}

.result-action {
  color: #409eff;
  font-size: 14px;
  font-weight: 500;
}

/* 搜索建议 */
.search-suggestions {
  padding: 20px 30px;
}

.suggestions-header {
  margin-bottom: 20px;
}

.suggestions-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.suggestions-list {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 12px;
}

.suggestion-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.suggestion-item:hover {
  background: #f5f7fa;
}

.suggestion-icon {
  font-size: 20px;
}

.suggestion-text {
  font-size: 14px;
  color: #606266;
}

/* 搜索遮罩层 */
.search-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 1001;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-header {
    padding: 15px 20px;
  }
  
  .search-filters {
    padding: 10px 20px;
  }
  
  .search-results,
  .search-suggestions {
    padding: 15px 20px;
  }
  
  .suggestions-list {
    grid-template-columns: 1fr;
  }
}
</style> 